package com.my.adminservice.map.service.impl;
import com.my.adminapi.map.mapconstants.Constants;
import com.my.adminservice.map.domain.dto.GeoResultDTO;
import com.my.adminservice.map.domain.dto.LocationDTO;
import com.my.adminservice.map.domain.dto.PoiListDTO;
import com.my.adminservice.map.domain.dto.SuggestSearchDTO;
import com.my.adminservice.map.service.IMapProvider;
import com.my.mycommondomain.domian.ResultCode;
import com.my.mycommondomain.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
@RefreshScope
@ConditionalOnProperty(value = "map.type" ,havingValue = "qqmap")
public class MapProviderImpl implements IMapProvider {

    /**
     * 腾讯位置服务域名
     */
    @Value("${qqmap.apiServer}")
    private String apiServer;

    @Value("${qqmap.key}")
    private String key;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据关键词搜索地点
     * @param suggestSearchDTO 搜索条件
     * @return 搜索结果
     */
    @Override
    public PoiListDTO searchQQMapPlaceByRegion(SuggestSearchDTO suggestSearchDTO) {
        //构建url
        String url=String.format(apiServer+ Constants.MAP_API_PLACE_SUGGESTION+
                "?key=%s&region=%s&region_fix=1&page_index=%s&page_size=%s&keyword=%s",key,suggestSearchDTO.getId(),
                suggestSearchDTO.getPageIndex(),suggestSearchDTO.getPageSize(),suggestSearchDTO.getKeyword());

        //请求并接收结果和转换
        ResponseEntity<PoiListDTO> response = restTemplate.getForEntity(url, PoiListDTO.class);
        if(!response.getStatusCode().is2xxSuccessful()){
            log.error("获取关键词查询结果异常:{}",response);
            throw new ServiceException(ResultCode.QQMAP_QUERY_FAILED.getMsg(),ResultCode.QQMAP_QUERY_FAILED.getCode());
        }
        return response.getBody();
    }

    /**
     * 根据经纬度来获取区域信息
     * @param locationDTO 经纬度
     * @return 区域信息
     */
    @Override
    public GeoResultDTO getQQMapDistrictByLonLat(LocationDTO locationDTO) {
        //构建url
        String url =String.format(apiServer+Constants.QQMAP_GEOCODER+
                "?key=%s&location=%s",key,locationDTO.formatInfo());
        ResponseEntity<GeoResultDTO> response = restTemplate.getForEntity(url, GeoResultDTO.class);
        if(!response.getStatusCode().is2xxSuccessful()){
            log.error("通过经纬度查询结果异常:{}",response);
            throw new ServiceException(ResultCode.QQMAP_QUERY_FAILED.getMsg(),ResultCode.TOKEN_EMPTY.getCode());
        }
        return response.getBody();
    }
}
